package middleaware

import (
	"lion-passport/internal/token"
	"lion-passport/internal/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Get the token from the request header
		accessToken := c.GetHeader("access_token")
		if accessToken == "" {
			c.JSON(http.StatusOK, utils.RespError(305208, "unauthorized"))
			c.Abort()
			return
		}

		claims, err := token.ParseToken(accessToken)
		if err != nil {
			c.JSON(http.StatusOK, utils.RespError(305208, "unauthorized"))
			c.Abort()
			return
		}

		c.Request = c.Request.WithContext(utils.NewContext(c.Request.Context(), &utils.UserInfo{
			Id: int32(claims.UserId),
		}))

		// If the token is valid, proceed to the next handler
		c.Next()
	}
}
